<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/20
 * Time: 13:19
 */

namespace App\Http\Controllers\Api;

use App\Helpers\Api\ApiResponse;
use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\Device;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Symfony\Component\HttpFoundation\Response as FoundationResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;


class DeviceController extends ApiController
{
    /**
     * @apiPermission none
     * @apiPermission anyone
     * @apiGroup Account
     * @api {get} /api/v1/getAccount 获取一个账号
     * @apiName getAccount
     * @apiVersion 1.0.0
     * @apiDescription app 获取一个账号
     * @apiParam {String} machine 机器de码
     * @apiParam {int} status   状态码
     * @apiSuccess {json} Success-Response:
     * { "result": "测试" ,"status_code":0}
     * @apiSampleRequest /api/v1/getAccount
     */
    public function getAccount(Request $request)
    {
        ini_set('default_socket_timeout', -1);
        try {
//            $this -> apiValidate($request , [
//                'machine' => "required",
//                'status' =>"required",
//            ]);
            $redis = app("redis");
            $status =$request->get("status");
//           $fp = fopen("getacc.txt", "w");
//           if (!flock($fp, LOCK_EX)) {
//               file_put_contents('bingfa.txt' , var_export('6666', true));
//               return $this->error("系统繁忙，请稍后再试");
//           }
            //找出符合条件的账号(只有email未知)
            $accounts =$redis->rpop("account:list:".$status);
            if(!$accounts){
                return $this->error("合适的账号不存在");
            }
            $key = "msg:account:".$accounts;
            $account = $redis->hgetall($key);
            $data = [
                //设备相关
                'email' => $account['email'],
                'cert' => $account['cert'],
                'password' => $account['password'],
                'Record_at' => $account['Record_at'],
            ];
            if (count($data)==0){
//               flock($fp, LOCK_UN);
                return $this->error("合适的账号不存在");
            }
            $log['now_time'] =Carbon::now()->toDateTimeString();
            $log['email'] =$account['email'];
            $log['status'] =$status;
            $redis -> hmset("old:account:".$account['email'] , $log);
//           flock($fp, LOCK_UN);
            return $this->success($data);
        } catch (\Exception $e) {
            return $this -> error($e ->getMessage());
        }

    }

    /**
     * @apiPermission none
     * @apiPermission anyone
     * @apiGroup Account
     * @api {post} /api/v1/replyAccount 回执账号
     * @apiName replyAccount
     * @apiVersion 1.0.0
     * @apiParam {String} email 账号
     * @apiParam {String} cert  证书码
     * @apiParam {String} status  状态
     * @apiParam {int} is   是否需要记录时间
     * @apiSuccess {json} Success-Response:
     * { "result": "测试" ,"status_code":0}
     * @apiSampleRequest /api/v1/replyAccount
     */
    public function replyAccount(Request $request){
        try {
//            $this -> apiValidate($request , [
//                'email' => "required",
//                'status' =>"required",
//            ]);
            ini_set('default_socket_timeout', -1);
            $redis = app("redis");
            $email =$request->get("email");
            $status =$request->get("status");
//            $fp = fopen("replyacc.txt", "w");
//           if (!flock($fp, LOCK_EX)) {
//               return $this->error("系统繁忙，请稍后再试");
//           }
            $key = "msg:account:".$email;
            $account = $redis->hgetall("msg:account:".$email);
            if(!$account){
//                 flock($fp, LOCK_UN);
                return $this->error("账号不存在");
            }
            $redis->hset($key,"cert",$request->get("cert"));
            $redis->hset($key,"status",$status);
            if($request->get("is") ==1){
                $redis->hset($key,"Record_at",time());
            }
            $redis->hset($key,"updated_at",Carbon::now()->toDateTimeString());
            $data = [
                'message' => '回执成功',
            ];
            //加入列表中
            $key ="account:list:".$status;
            $redis->rpush($key,$email);
//                 flock($fp, LOCK_UN);
            return $this->success($data);
        } catch (\Exception $e) {
            return $this -> error($e ->getMessage());
        }
    }


    /**
     * @apiPermission none
     * @apiPermission anyone
     * @apiGroup New
     * @api {get} /api/v1/getNewDevice 1.获取一个设备
     * @apiName getNewDevice
     * @apiVersion 1.0.0
     * @apiDescription app 获取一个设备
     * @apiParam {String} machines 机器码
     * @apiParam {String} ProductType 设备型号
     * @apiParam {int} status 设备状态
     * @apiSuccess {json} Success-Response:
     * { "result": "测试" ,"status_code":0}
     * @apiSampleRequest /api/v1/getNewDevice
     */
    public function getNewDevice(Request $request)
    {
        try {
//            $this -> apiValidate($request , [
//                'machines' => "required",
//                'ProductType' =>"required",
//                'status' =>"required",
//            ]);
            ini_set('default_socket_timeout', -1);

            $redis = app("redis");
            $tp =$request->get("ProductType");
            $status =$request->get("status");
//             $fp = fopen("getde.txt", "w");
//           if (!flock($fp, LOCK_EX)) {
//               return $this->error("系统繁忙，请稍后再试");
//           }
//            if($status==900){
//                $status =908;
//            }
            $key="device:list:".$status.':'.$tp;
            $device =$redis->lpop($key);
            if(!$device){
//                flock($fp, LOCK_UN);
                return $this->error("暂时没有可用的设备码");
            }
            $code = $redis->hgetall("msg:device:".$device);
            $data = [
                //设备相关
                'udid' => $code['udid'],
                'BluetoothAddress' => $code['bt'],
                'Imei' => $code['imei'],
                'WiFiAddress' => $code['wifi'],
                'ecid' => $code['ecid'],
                'ProductType' => $code['tp'],
                'ModelNumber' => $code['nb'],
                'RegionInfo' => $code['reg'],
                'serial' => $code['sn'],
                'Ethernet' => $code['ethernet'],
                'ICCID' => $code['iccid'],
                'IMSI' => $code['IMSI'],
                'BasebandSerialNumber' => $code['BasebandSerialNumber'],
                'BasebandMasterKeyHash' => $code['BasebandMasterKeyHash'],
                'BasebandChipID' => $code['BasebandChipID'],
                'Record_at' => $code['Record_at'],
            ];
            if (count($data)==0){
//                flock($fp, LOCK_UN);
                return $this->error("合适的账号不存在");
            }
            //加入对象 （5分钟同步一次） 把5分钟没有回执的加回列表
            $log['now_time'] =Carbon::now()->toDateTimeString();
            $log['sn'] =$code['sn'];
            $log['tp'] =$code['tp'];
            $log['status'] =$status;
            $redis -> hmset("old:device:".$code['sn'] , $log);
//             flock($fp, LOCK_UN);
            return $this->success($data);
        } catch (\Exception $e) {
            return $this -> error($e ->getMessage());

        }
    }

    /**
     * @apiPermission none
     * @apiPermission anyone
     * @apiGroup New
     * @api {get} /api/v1/replyNewDevice 2.回执设备
     * @apiName replyNewDevice
     * @apiVersion 1.0.0
     * @apiDescription app 回执设备
     * @apiParam {String} serial 设备serial
     * @apiParam {int} status  状态
     * @apiParam {int} is  是否需要记录时间1 记录
     * @apiParam {String} ProductType 设备型号
     * @apiSuccess {json} Success-Response:
     * { "result": "测试" ,"status_code":0}
     * @apiSampleRequest /api/v1/replyNewDevice
     */

    public function replyNewDevice(Request $request){
        try {
//            $this -> apiValidate($request , [
//                'serial' => "required",
//                'status' =>"required",
//                'ProductType'=>"required",
//            ]);
            ini_set('default_socket_timeout', -1);
            $redis = app("redis");
            $sn =$request->get("serial");
            $tp =$request->get("ProductType");
            $status =$request->get("status");
//            $fp = fopen("replyde.txt", "w");
//           if (!flock($fp, LOCK_EX)) {
//               return $this->error("系统繁忙，请稍后再试");
//           }
            if($status==908){
                $status =911;
            }
            $key ="msg:device:".$sn;
            $code =$redis->hgetall($key);
            if ($code) {
                $data = [
                    'message' => '回执成功',
                ];
                $redis->hset($key,"status",$status);
                $redis->hset($key,"updated_at",Carbon::now()->toDateTimeString());
                if($request->get("is") ==1){
                    $redis->hset($key,"Record_at",time());
                }
                $key ="device:list:".$status.":".$tp;
                $redis->rpush($key,$sn);
//                 flock($fp, LOCK_UN);
                return $this->success($data);
            }
//             flock($fp, LOCK_UN);
            return $this->error("合适的设备不存在");
        } catch (\Exception $e) {
            return $this -> error($e ->getMessage());
        }
    }
    

}